//
//  NetWorkTools.swift
//  JJWeibo
//
//  Created by JJ on 15/9/2.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit
import AFNetworking
import ReactiveCocoa

enum RequestMethod:String{
    
    case GET="GET"
    case POST="POST"
}

class NetWorkTools: AFHTTPSessionManager {
    
   private let client_id="4094600843"
   let redirect_uri="http://www.baidu.com/"
    private let AppSecret="300c83219857b221b1f5a3a86de85edf"
    
    var oathUrl:NSURL{
        let urlString="https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        
        return NSURL(string: urlString)!
    }
    
    func loadReccessToKen(code:String)->RACSignal{
        let url="https://api.weibo.com/oauth2/access_token"
        
        let paramters=["client_id":client_id,
            "client_secret":AppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirect_uri
        ]
        return request(.POST, urlString: url, parameters: paramters,withToken:false)
    }
    
    func loadUserInfo(uid:String)->RACSignal{
        let url="https://api.weibo.com/2/users/show.json"
        let paramters=["uid":uid]
        return request(.GET, urlString: url, parameters: paramters)
    }
    
    func loadStatus(since_id since_id: Int, max_id: Int)->RACSignal{
        
        let url="https://api.weibo.com/2/statuses/home_timeline.json"
        var paramters=[String:AnyObject]()
        
        if since_id>0{
            paramters["since_id"]=since_id
        }else if max_id>0{
            paramters["max_id"]=max_id-1
        }
        return request(.GET, urlString: url, parameters: paramters)
    }
    
    func senStatus(status:String,image:UIImage?)->RACSignal{
        let paramters=["status":status]
        if image == nil {

            return request(.POST, urlString: "https://api.weibo.com/2/statuses/update.json", parameters: paramters)
            
        } else {
    
            return upload("https://upload.api.weibo.com/2/statuses/upload.json", parameters: paramters, image: image!)
        }
    }
    static let shareNetWorkTools:NetWorkTools={
        
        var instance=NetWorkTools(baseURL: nil)
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
    private func appendToken(inout parameters:[String: AnyObject]? )->Bool{
        
        guard let token=UserAccountViewModel.sharedUserAccount.accessToken else{
            return false
        }
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        parameters!["access_token"]=token
        return true
    }
    
    private func request(method:RequestMethod,urlString:String, var parameters:[String: AnyObject]?,withToken:Bool=true)->RACSignal{
    
        return RACSignal.createSignal({ (subcriber) -> RACDisposable! in
            
            if withToken && !self.appendToken(&parameters){
                subcriber.sendError(NSError(domain: "com.itheima.error", code: -1001, userInfo: ["errorMessage": "Token 为空"]))
                return nil
            }
            
            let successBack={ (task:NSURLSessionDataTask,resualt:AnyObject) -> Void in
                
                subcriber.sendNext(resualt)
                subcriber.sendCompleted()
            }
            
            let failureBack={(task:NSURLSessionDataTask,error:NSError) -> Void in
            
                subcriber.sendError(error)
            }
            
           if method == .GET
           {
                self.GET(urlString, parameters: parameters, success: successBack, failure: failureBack)
           }else
           {
                self.POST(urlString, parameters: parameters, success: successBack, failure: failureBack)
            }
            return nil
        })
    }
    
    
    private func upload(URLString: String, var parameters: [String: AnyObject]?, image: UIImage) -> RACSignal{
        
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            
            if !self.appendToken(&parameters) {
                subscriber.sendError(NSError(domain: "com.itheima.error", code: -1001, userInfo: ["errorMessage": "Token 为空"]))
                return nil
            }
            
            self.POST(URLString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                
                let data=UIImagePNGRepresentation(image)!
                formData.appendPartWithFileData(data, name: "pic", fileName: "ohoh", mimeType: "application/octet-stream")
                
                }, success: { (_, resualt) -> Void in
                    
                    subscriber.sendNext(resualt)
                    subscriber.sendCompleted()
                    
                }, failure: { (_, error) -> Void in
                    
                    subscriber.sendError(error)

            })
            return nil
        })
        
    }

}
